package com.marisfrolg.storage;

import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnKey;
import com.marisfrolg.base.BaseApplication;
import com.marisfrolg.entity.EnquiryOrder;
import com.marisfrolg.entity.EnquiryOrderItem;
import com.marisfrolg.entity.PickOutInfo;
import com.marisfrolg.entity.json.JsonEnquiryOrder;
import com.marisfrolg.entity.json.JsonEnquiryOrderItem;
import com.marisfrolg.entity.json.TohuIn;
import com.marisfrolg.entity.json.TohuOut;
import com.marisfrolg.entity.json.TohuOutMessage;
import com.marisfrolg.entity.json.User;
import com.marisfrolg.entity.json.WoQueue;
import com.marisfrolg.ui.ProgressBarWithText;
import com.marisfrolg.util.ReadCodeController;
import com.marisfrolg.util.StringUtil;
import com.marisfrolg.util.WebServicesUtil;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class PickoutActivity extends ItemActivity {
	@ViewInject(R.id.wonotext)
	TextView wonotext;
	@ViewInject(R.id.wonoedit)
	BootstrapEditText wonoedit;
	@ViewInject(R.id.taskpage)
	LinearLayout taskpage;
	@ViewInject(R.id.choosequeue)
	BootstrapButton choosequeue;
//	showresult=(BootstrapButton)findViewById(R.id.showresult);
	private WSHandler wHandler;
	private WebServicesUtil ws;
	private LayoutInflater inflater;
	private EnquiryOrder eo;
	private List<EnquiryOrderItem> eois;
	private String lastSbinno="";
	private final static String READCODEVALUE="READCODEVALUE";
	private final static String FOCUSVIEW="FOCUSVIEW";
	private final static int AUTOREAD=3010;
	private final static int CONTINUEWORK=3000;
	BootstrapEditText ctnnoedit;
	TextView ctntype;
	LinearLayout tasklistpage;
	LinearLayout tasklist;
	ScrollView tasklistscroll;
	View nowFocus;
	BootstrapButton submit;
	@ViewInject(R.id.showresult)
	BootstrapButton showresult;
	@ViewInject(R.id.cancel)
	BootstrapButton cancel;
	PopupWindow popWindow;
	
	private ReadCodeController rcc;
	
	private int itemmargin=10;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pickout);
		sHandler=new ScanHandler(this);
		wHandler=new WSHandler(this);
		rcc=((BaseApplication)getApplication()).getReadCodeController();
		rcc.setHandler(sHandler);
		rcc.Open();
		ws=new WebServicesUtil(this,wHandler);
		inflater = LayoutInflater.from(this);
		ViewUtils.inject(this);
		//是否继续之前工作
		try {
			eo = db.findFirst(Selector.from(EnquiryOrder.class));
			eois=db.findAll(Selector.from(EnquiryOrderItem.class).orderBy("whoseq", false));
			if(eo==null){
				PickOutInfo poi=db.findFirst(PickOutInfo.class);
				if(poi!=null&&poi.isQueue()){
					getWoByQueueName(poi.getQueuename());
				}
			}else{
				Message msg=new Message();
				msg.what=WebServicesUtil.ACTION_GetWHO;
				msg.arg1=CONTINUEWORK;
				wonoedit.setText(eo.getWono());
				wHandler.dispatchMessage(msg);
			}
			initResultWindow();
			//取消按钮
			cancel.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					new AlertDialog.Builder(PickoutActivity.this).setPositiveButton("确定",new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int which) {
							try {
								HashMap<String , Object>params=new HashMap<String, Object>();
								EnquiryOrder eo=db.findFirst(EnquiryOrder.class);
								params.put("WHO_NO", eo==null?"":eo.getWho());
								Gson gson=new Gson();
								Type type = new TypeToken<User>() {}.getType();
								params.put("USER", gson.toJson(loginUser, type));
								ws.call(WebServicesUtil.ACTION_LOGOUT, params, WebServicesUtil.URL_ACTION_LOGOUT, WebServicesUtil.METHOD_ACTION_LOGOUT);
							} catch (DbException e) {
								e.printStackTrace();
							}
						}
					}).setNegativeButton("取消", null).setTitle("警告").setMessage("之前的操作将清零,重新开始工作").show();
				}
			});
		} catch (DbException e) {
			e.printStackTrace();
		}
		scrollview();
	}
	@OnClick(R.id.wonotext)
	public void showwodetail(View v){
		if(eo!=null){
			String text="WO No. : "+eo.getWho()+"\nAA : "+eo.getAreawho()+"\nPHUs : ?\n拣配处理单位 : ?PkMt LP?";
			Toast t=Toast.makeText(this, text, Toast.LENGTH_LONG);
			t.show();
		}
		scrollview();
	}
	@OnClick(R.id.jianpeititle)
	public void titleClick(View v){
		scrollview();
	}
	
	private void scrollview(){
		try {
			eo = db.findFirst(Selector.from(EnquiryOrder.class));
			eois=db.findAll(Selector.from(EnquiryOrderItem.class).orderBy("whoseq", false));
		} catch (DbException e) {
			e.printStackTrace();
		}
		if(eo==null){
			return;
		}
		if(!StringUtil.isEmpty(eo.getWho())){
			if(StringUtil.isEmpty(eo.getCtnno())&&(!eo.getPackmatnr().endsWith("9"))){
				ctnnoedit.requestFocus();
			}else{
				int j=0;
				if(eois!=null){
					for (EnquiryOrderItem eoi : eois) {
						if(eoi.getStatus()!=2){
							break;
						}
						j++;
					}
					View focus=null;
					if(tasklist==null||tasklist.getChildAt(j)==null){
						return;
					}
					if(eois.get(j).getStatus()==0){
						focus=tasklist.getChildAt(j).findViewById(R.id.sbinedit);
					}else if(eois.get(j).getStatus()==1){
						focus=tasklist.getChildAt(j).findViewById(R.id.productedit);
					}
					int height=0;
					height+=(tasklist.getChildAt(j).getHeight()+itemmargin)*j;
					tasklistscroll.smoothScrollTo( 0, height>40?height-40:height);
					focus.requestFocus();
				}
			}
		}
	}
	@OnClick(R.id.choosequeue)
	public void chooseQueue(View v){
		HashMap<String , Object>params=new HashMap<String, Object>();
		Gson gson=new Gson();
		Type type = new TypeToken<User>() {}.getType();
		params.put("USER", gson.toJson(loginUser, type));
		progressDialog = ProgressDialog.show(PickoutActivity.this, "查询中", "请稍候...", true, true);
		ws.call(WebServicesUtil.ACTION_getQUEUE, params, WebServicesUtil.URL_ACTION_getQUEUE, WebServicesUtil.METHOD_ACTION_getQUEUE);
	}
	@OnKey(R.id.wonoedit)//完成仓库订单号
	public void wonoFinish(View v, int keyCode, KeyEvent event){	
		if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_UP){
			wonoedit.setText(wonoedit.getText().toString().trim().toUpperCase(Locale.US));
			Message msg=new Message();
			msg.what=ReadCodeController.CODEREAD;
			Map<String,Object> params=new HashMap<String, Object>();
			params.put(READCODEVALUE, wonoedit.getText());
			params.put(FOCUSVIEW, v);
			msg.obj=params;
			sHandler.dispatchMessage(msg);
		}
	}
	private void refreshTotalProgress(){
		ProgressBarWithText p=(ProgressBarWithText)findViewById(R.id.totaltaskprogress);
		if(p!=null){
			try{
				List<EnquiryOrderItem> es=db.findAll(EnquiryOrderItem.class);
				int sum=0;
				int pro=0;
				for (EnquiryOrderItem enquiryOrderItem : es) {
					sum+=enquiryOrderItem.allquantity;
					pro+=enquiryOrderItem.quantity;
				}
				p.setMax(sum);
				p.setProgress(pro);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	private void showTaskPage(){
		taskpage.removeAllViews();
		View task = inflater.inflate(R.layout.pickout_taskpage, null);
		task.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
		taskpage.addView(task);
		ctnnoedit=(BootstrapEditText)task.findViewById(R.id.ctnnoedit);
		TextView xianghaotitle=(TextView)task.findViewById(R.id.xianghaotitle);
//		ViewUtils.inject(ctnnoedit);
		ctnnoedit.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_UP){
					ctnnoedit.setText(ctnnoedit.getText().toString().trim().toUpperCase(Locale.US));
					Message msg=new Message();
					msg.what=ReadCodeController.CODEREAD;
					Map<String,Object> params=new HashMap<String, Object>();
					params.put(READCODEVALUE, ctnnoedit.getText());
					params.put(FOCUSVIEW, v);
					msg.obj=params;
					sHandler.dispatchMessage(msg);
				}
				return false;
			}
		});
		xianghaotitle.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View v) {
				try{
					EnquiryOrder eo=db.findFirst(EnquiryOrder.class);
					eo.setCtnno("");
					if(eo.getPackmatnr().endsWith("9")){
						return false;
					}
					db.update(eo, "ctnno");
					ctnnoedit.setText("");
					ctnnoedit.setEnabled(true);
					play_sound(true);
				}catch(Exception e){
					e.printStackTrace();
				}
				return false;
			}
		});
		ctnnoedit.setEnabled(!eo.isEnded());//若已提交停止使用控件
		
		try {
			ctntype=(TextView)task.findViewById(R.id.ctntype);
			EnquiryOrder eo=db.findFirst(EnquiryOrder.class);
			ctntype.setText(eo.getPackmatnr());
			tasklistpage=(LinearLayout)task.findViewById(R.id.tasklistpage);
			if(!eo.getPackmatnr().endsWith("0")){
				ctnnoedit.setEnabled(false);
			}else{
				ctnnoedit.requestFocus();
			}
			showTaskListPage();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void showTaskListPage() throws DbException{
		tasklistpage.removeAllViews();
		eo=db.findFirst(Selector.from(EnquiryOrder.class));//.where(WhereBuilder.b("wono", "=", wonotext.getText()+"")));
		View task = inflater.inflate(R.layout.pickout_tasklistpage, null);
		task.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
		tasklistpage.addView(task);
		tasklist=(LinearLayout)task.findViewById(R.id.tasklist);
		tasklistscroll=(ScrollView)task.findViewById(R.id.tasklistscroll);
		//提交按钮
		submit=(BootstrapButton)findViewById(R.id.submit);
		submit.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try {
					eo=db.findFirst(Selector.from(EnquiryOrder.class));
					List<EnquiryOrderItem>eois=db.findAll(Selector.from(EnquiryOrderItem.class).orderBy("seq", false));
					List<JsonEnquiryOrderItem> jeois=new ArrayList<JsonEnquiryOrderItem>();
					int sum=0;
					int usum=0;
					for (int i=0;i<eois.size();i++) {
						JsonEnquiryOrderItem jeoi=new JsonEnquiryOrderItem(eois.get(i));
						sum+=jeoi.getVSOLM();
						usum+=jeoi.getKQUAN();
						jeois.add(jeoi);
					}
					TohuIn ti=new TohuIn(eo);
					ti.setITEMS(jeois);
					ti.setBNAME(loginUser.getUsername());
					ti.setWO(eo.getWho());
					
					final Gson gson=new Gson();
					final String json=gson.toJson(ti);
					if((!eo.getPackmatnr().endsWith("9"))&&StringUtil.isEmpty(eo.getCtnno())||usum==0){
						Toast.makeText(PickoutActivity.this, "没箱号或者未拣任何货物", Toast.LENGTH_LONG).show();
						play_sound(false);
						return;
					}
					AlertDialog.Builder alert=new AlertDialog.Builder(PickoutActivity.this).setTitle("提示").setMessage("是否确认提交("+usum+"/"+sum+")");
					String desc="";
					if(sum!=usum){
						play_sound();
						desc="差异";
						alert.setNeutralButton("拆分", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								Map<String,Object> params=new HashMap<String, Object>();
								params.put("TOHUIN", json);
								Type type = new TypeToken<User>() {}.getType();
								params.put("USER", gson.toJson(loginUser, type));
								params.put("SPLTMK", "X");
								progressDialog = ProgressDialog.show(PickoutActivity.this, "提交中", "请稍候...", true, true);
								progressDialog.setCanceledOnTouchOutside(false);
								progressDialog.setOnCancelListener(new OnCancelListener() {
									public void onCancel(DialogInterface dialog) {
										WebServicesUtil.setConnectionTimeOut();
									}
								});
								ws.call(WebServicesUtil.ACTION_SubmitWHO, params, WebServicesUtil.URL_ACTION_SubmitWHO, WebServicesUtil.METHOD_ACTION_SubmitWHO);
							}
						});
					}
					alert.setPositiveButton(desc+"提交", new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int which) {
							Map<String,Object> params=new HashMap<String, Object>();
							params.put("TOHUIN", json);
							Type type = new TypeToken<User>() {}.getType();
							params.put("USER", gson.toJson(loginUser, type));
							progressDialog = ProgressDialog.show(PickoutActivity.this, "提交中", "请稍候...", true, true);
							progressDialog.setCanceledOnTouchOutside(false);
							progressDialog.setOnCancelListener(new OnCancelListener() {
								public void onCancel(DialogInterface dialog) {
									WebServicesUtil.setConnectionTimeOut();
								}
							});
							ws.call(WebServicesUtil.ACTION_SubmitWHO, params, WebServicesUtil.URL_ACTION_SubmitWHO, WebServicesUtil.METHOD_ACTION_SubmitWHO);
						}
					}).setNegativeButton("取消", null);
					alert.show();
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
		});
		OnFocusChangeListener oal=new OnFocusChangeListener(){
			public void onFocusChange(View v, boolean hasFocus) {
				BootstrapEditText bet;
				if(hasFocus&&v.getId()==R.id.productedit){//产品框获取到焦点,验证是否已有仓位
					bet=(BootstrapEditText)((RelativeLayout) v.getParent()).findViewById(R.id.sbinedit);
					if(StringUtil.isEmpty(bet.getText().toString())){
						bet.requestFocus();
					}
				}else if((!hasFocus)&&v.getId()==R.id.sbinedit){//仓位框失去焦点提交仓位
					bet=(BootstrapEditText)v;
					if(!StringUtil.isEmpty(bet.getText()+"")){
						Message msg=new Message();
						Map<String,Object> params=new HashMap<String, Object>();
						params.put(READCODEVALUE, bet.getText()+"");
						params.put(FOCUSVIEW, v);
						msg.obj=params;
						msg.what=ReadCodeController.CODEREAD;
						sHandler.dispatchMessage(msg);
					}
				}
			}
		};
		tasklist.removeAllViews();
		//找到正在进行的第一个任务获取焦点
		boolean hasFocus=false;
		//是否已经有箱号,继续工作则自动补充之前箱号
		Message msg=new Message();
		if(!StringUtil.isEmpty(eo.getCtnno())){
			ctnnoedit.setText(eo.getCtnno());
			msg.what=ReadCodeController.CODEREAD;
			msg.arg1=AUTOREAD;
			Map<String,Object> params=new HashMap<String, Object>();
			params.put(READCODEVALUE, eo.getCtnno());
			params.put(FOCUSVIEW, ctnnoedit);
			msg.obj=params;
			sHandler.dispatchMessage(msg);
		}else if(ctnnoedit.isEnabled()){
			hasFocus=true;
		}
		//遍历生成各个任务点
//		View focus=null;
//		int focusSeq=-1;
//		int j=0;
		eois=db.findAll(Selector.from(EnquiryOrderItem.class).orderBy("whoseq", false));
		if(eois==null){
			return;
		}
		for (EnquiryOrderItem eoi : eois) {
			View taskitem = inflater.inflate(R.layout.pickout_tasklist, null);
			tasklist.addView(taskitem);
			LinearLayout.LayoutParams layoutParams=(LinearLayout.LayoutParams)taskitem.getLayoutParams();
			layoutParams.topMargin=itemmargin;
			//仓位
			TextView sbinstatus=(TextView)taskitem.findViewById(R.id.sbinstatus);
			BootstrapEditText sbinedit=(BootstrapEditText)taskitem.findViewById(R.id.sbinedit);
			sbinedit.setOnFocusChangeListener(oal);
			sbinedit.setEnabled(!eo.isEnded());//若已提交停止使用控件
			TextView sbintip=(TextView)taskitem.findViewById(R.id.sbintip);
			sbintip.setText(eoi.getSbinno());
			sbinedit.setHint(eoi.getSbinno());
			sbinedit.setText(eoi.getSbinnocheck());
			sbinstatus.setText(eoi.getSbinnocheck());
			//确定按钮
			BootstrapButton confirm=(BootstrapButton)taskitem.findViewById(R.id.confirm);
			ConfirmListener c=new ConfirmListener();
			confirm.setOnClickListener(c);
			confirm.setEnabled(!eo.isEnded());//若已提交停止使用控件
			BootstrapButton reduce=(BootstrapButton)taskitem.findViewById(R.id.reduce);
			ReduceListener r=new ReduceListener();
			reduce.setOnClickListener(r);
			reduce.setEnabled(!eo.isEnded());//若已提交停止使用控件
			//序列号
			TextView seq=(TextView)taskitem.findViewById(R.id.seq);
			seq.setText(eoi.getWhoseq()+"");
			//状态
			TextView taskstatus=(TextView)taskitem.findViewById(R.id.taskstatus);
			taskstatus.setText(EnquiryOrderItem.STATUSDESC[eoi.getStatus()]);
			//伙伴地址
			TextView descrip=(TextView)taskitem.findViewById(R.id.descrip);
			descrip.setText(eoi.getDescrip());
			//进度条
			ProgressBarWithText taskprogress=(ProgressBarWithText)taskitem.findViewById(R.id.taskprogress);
			taskprogress.setMax(eoi.getAllquantity());
			taskprogress.setProgress(eoi.getQuantity());
			//产品输入框
			BootstrapEditText productedit=(BootstrapEditText)taskitem.findViewById(R.id.productedit);
			productedit.setOnFocusChangeListener(oal);
			productedit.setEnabled(!eo.isEnded());//若已提交停止使用控件
			TextView producttextview=(TextView)taskitem.findViewById(R.id.producttextview);
			producttextview.setText(eoi.getProductno());
			//产品描述
			TextView productdisc=(TextView)taskitem.findViewById(R.id.productdisc);
			productdisc.setText(eoi.getMaktx());
//			if(!hasFocus&&eoi.getStatus()!=2){
//				focusSeq=j;
//				hasFocus=true;
//			}
//			j++;
		}
//		if((!hasFocus)&&focusSeq==-1){//箱号和工作都完成
//			focus=submit;
//		}else if(focusSeq!=-1){//箱号完成
//			if(eois.get(focusSeq).getStatus()==0){
//				focus=tasklist.getChildAt(focusSeq).findViewById(R.id.sbinedit);
//			}else if(eois.get(focusSeq).getStatus()==1){
//				focus=tasklist.getChildAt(focusSeq).findViewById(R.id.productedit);
//			}
//		}
//		if(focus!=null){
//			focus.requestFocus();
//		}
//		tasklistscroll.smoothScrollTo(0, 10);
		//如果已经处理完成
		if(eo.isEnded()){
			submit.setVisibility(View.GONE);
			initResultWindow();
		}
		refreshTotalProgress();
//		scrollview();
	}
	@SuppressWarnings("deprecation")
	private void initResultWindow() throws DbException{
		final View vPopupWindow=inflater.inflate(R.layout.pickout_pop_window, null, false);
		vPopupWindow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		popWindow = new PopupWindow(vPopupWindow,500,700,true);
		popWindow.setOutsideTouchable(true);
		popWindow.setFocusable(true);
		popWindow.setBackgroundDrawable(new BitmapDrawable());
		showresult.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(popWindow.isShowing()){
					popWindow.dismiss();
				}else{
					popWindow.showAsDropDown(showresult);
				}
			}
		});
		TextView ctnno=(TextView) vPopupWindow.findViewById(R.id.ctnno);
		TextView newwono=(TextView) vPopupWindow.findViewById(R.id.newwono);
		TohuOut to=db.findFirst(TohuOut.class);
		if(to!=null){
			ctnno.setText(to.getOUTPUT_HUIDENT());
			newwono.setText(to.getLT_WHO());
		}
		LinearLayout resultList=(LinearLayout)vPopupWindow.findViewById(R.id.resultList);
		List<TohuOutMessage> msgs=db.findAll(Selector.from(TohuOutMessage.class).orderBy("id"));
		if(msgs==null||msgs.size()==0){
			return;
		}
		boolean hasError=false;
		for (TohuOutMessage tohuOutMessage : msgs) {
			View msgview = inflater.inflate(R.layout.pickout_pop_item, null);
			TextView msgid=(TextView)msgview.findViewById(R.id.msgid);
			msgid.setText(""+tohuOutMessage.getID());
			TextView msgnum=(TextView)msgview.findViewById(R.id.msgnum);
			msgnum.setText(""+tohuOutMessage.getNUMBER());
			TextView msgtext=(TextView)msgview.findViewById(R.id.msgtext);
			msgtext.setText(""+tohuOutMessage.getMESSAGE());
			TextView msgtype=(TextView)msgview.findViewById(R.id.msgtype);
			msgtype.setText(""+tohuOutMessage.getTYPE());
			tohuOutMessage.getID();
			if(tohuOutMessage.getTYPE().contains("E")){//失败
				msgview.setBackgroundResource(R.drawable.item_bg_red);
				hasError=true;
			}else if(tohuOutMessage.getTYPE().contains("S")){//成功
				msgview.setBackgroundResource(R.drawable.item_bg_green);
			}else{//其他
				msgview.setBackgroundResource(R.drawable.item_bg_blue);
			}
			resultList.addView(msgview);
			LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) msgview.getLayoutParams();
			lp.topMargin = 10;
		}
		if(hasError){
			showresult.setBootstrapType("danger");
			play_sound(false);
			new AlertDialog.Builder(PickoutActivity.this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					if(popWindow.isShowing()){
						popWindow.dismiss();
					}else{
						popWindow.showAsDropDown(showresult);
					}
				}
			}).setTitle("提示").setMessage("提交结果中有错误").show();
		}
	}
	
	//核心处理:根据输入时焦点处理过程-------------------------
	public void readcode(String code,View view,boolean sout) throws DbException{
		if(eo!=null&&eo.isEnded()){
			return;
		}
		code=code.toUpperCase(Locale.US).trim();
		View v=getCurrentFocus();
		if(v==null||v.getId()==R.id.confirm){//无焦点时,找到最近一次操作的焦点
			v=view;
			if(v==null){
				return;
			}
		}
		EditText et;
		View next=null;
		RelativeLayout taskitem;
		EnquiryOrderItem eoi;
		TextView seq;
		TextView taskstatus;
		EnquiryOrder eo;
		switch (v.getId()) {
		case R.id.wonoedit:
			HashMap<String , Object> params=new HashMap<String, Object>();
			params.put("WHO", code);
			Gson gson=new Gson();
			Type type = new TypeToken<User>() {}.getType();
			params.put("USER", gson.toJson(loginUser, type));
			progressDialog = ProgressDialog.show(PickoutActivity.this, "查询中", "请稍候...", true, true);
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.setOnCancelListener(new OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					WebServicesUtil.setConnectionTimeOut();
				}
			});
			ws.call(WebServicesUtil.ACTION_GetWHO, params, WebServicesUtil.URL_ACTION_GetWHO, WebServicesUtil.METHOD_ACTION_GetWHO);
			break;
		case R.id.ctnnoedit:
			eo=db.findFirst(Selector.from(EnquiryOrder.class));
			eo.setCtnno(code);
			db.update(eo, "ctnno");
			ctnnoedit.setText(code);
			ctnnoedit.setEnabled(false);
			if(sout){
				play_sound(true);
			}
			scrollview();
			break;
		case R.id.sbinedit:
			eo=db.findFirst(Selector.from(EnquiryOrder.class));
			et=(EditText)v;
			if((!eo.getPackmatnr().endsWith("9"))&&StringUtil.isEmpty(eo.getCtnno())){
				et.setText("");
				play_sound(false);
				Toast.makeText(this, "先输入箱号", Toast.LENGTH_SHORT).show();
				return;
			}
			taskitem=(RelativeLayout) v.getParent().getParent().getParent();
			BootstrapEditText sbinedit=(BootstrapEditText)taskitem.findViewById(R.id.sbinedit);
			TextView sbinstatus=(TextView)taskitem.findViewById(R.id.sbinstatus);
			boolean change=!sbinedit.getText().toString().equals(sbinedit.getHint().toString());
			if(!code.equals(sbinedit.getHint())){
				play_sound(false);
				sbinedit.setText("");
				Toast.makeText(this, "仓位不一致,请到相应仓位取货", Toast.LENGTH_SHORT).show();
				return;
			}
			taskstatus=(TextView)(taskitem).findViewById(R.id.taskstatus);
			seq=(TextView)taskitem.findViewById(R.id.seq);
			eoi= db.findFirst(Selector.from(EnquiryOrderItem.class).where(WhereBuilder.b("whoseq", "=", seq.getText()+"")));
			eoi.setSbinnocheck(code);
			lastSbinno=code;
			if(eoi.quantity==eoi.allquantity){
				eoi.setStatus(2);
			}else{
				eoi.setStatus(1);
			}
			db.update(eoi, "status","sbinnocheck");
			if(change){
				play_sound(true);
			}
			sbinstatus.setText(code);
			et.setText(eoi.getSbinnocheck());
			taskstatus.setText(EnquiryOrderItem.STATUSDESC[eoi.getStatus()]);
//			next=et.focusSearch(View.FOCUS_DOWN);
			next=taskitem.findViewById(R.id.productedit);
			next.requestFocus();
			break;
		case R.id.productedit:
			eo=db.findFirst(Selector.from(EnquiryOrder.class));
			et=(EditText)v;
			if((!eo.getPackmatnr().endsWith("9"))&&StringUtil.isEmpty(eo.getCtnno())){
				play_sound(false);
				et.setText("");
				Toast.makeText(this, "先输入箱号", Toast.LENGTH_SHORT).show();
				return;
			}
			taskitem=(RelativeLayout) v.getParent();
			ProgressBar p=(ProgressBar)taskitem.findViewById(R.id.taskprogress);
			taskstatus=(TextView)taskitem.findViewById(R.id.taskstatus);
			seq=(TextView)taskitem.findViewById(R.id.seq);
			eoi= db.findFirst(Selector.from(EnquiryOrderItem.class).where(WhereBuilder.b("whoseq", "=", seq.getText()+"")));
			if((!code.equals(eoi.getProductno()))){
				play_sound(false);
				et.setText("");
				Toast.makeText(this, "产品不匹配,请选择正确的商品", Toast.LENGTH_SHORT).show();
				break;
			}
			if(eoi.getQuantity()<eoi.getAllquantity()){
				eoi.setQuantity(eoi.getQuantity()+1);
				et.setText(code);
				p.setProgress(eoi.getQuantity());
				play_sound(true);
				if(eoi.getQuantity()==eoi.getAllquantity()){
					eoi.setStatus(2);
					db.update(eoi, "quantity","status");
					refreshTotalProgress();
				}else{
					db.update(eoi, "quantity");
					refreshTotalProgress();
					break;
				}
			}else{
				Toast.makeText(this, "此任务已完成", Toast.LENGTH_SHORT).show();
				play_sound(false);
			}
			taskstatus.setText(EnquiryOrderItem.STATUSDESC[eoi.getStatus()]);
//			next=et.focusSearch(View.FOCUS_DOWN);
			TextView sbintip=null;
			for(int i=0;i<tasklist.getChildCount();i++){
				if(tasklist.getChildAt(i)==taskitem){//最后一个任务不处理
					next=tasklist.getChildAt(i+1);
					if(next!=null){
						sbintip=(TextView)next.findViewById(R.id.sbintip);
						next=next.findViewById(R.id.sbinedit);
					}
					break;
				}
			}
			if(next==null){
				next=et.focusSearch(View.FOCUS_DOWN);
				break;
			}else if(next.getId()==R.id.confirm){
				next=next.focusSearch(View.FOCUS_DOWN);
			}
			try{//下一个仓位是否已填,已填则到产品
//				RelativeLayout ti=(RelativeLayout) next.getParent().getParent().getParent();
//				TextView ss=(TextView)ti.findViewById(R.id.taskstatus);
//				if(EnquiryOrderItem.STATUSDESC[1].equals(ss.getText()+"")){
//					next=next.focusSearch(View.FOCUS_DOWN);
//				}
				
				next.requestFocus();
			}catch (Exception e){
				e.printStackTrace();
			}
			//如果是上一次相同BIN则自动发送当前BINNO
			if(sbintip!=null&&next!=null&&next.getId()==R.id.sbinedit&&lastSbinno.equals(sbintip.getText()+"")){
				Message msg=new Message();
				msg.what=ReadCodeController.CODEREAD;
				params=new HashMap<String, Object>();
				params.put(READCODEVALUE,lastSbinno);
				params.put(FOCUSVIEW, next);
				msg.obj=params;
				sHandler.dispatchMessage(msg);
			}
			break;
		default:
			break;
		}
		//滚动
		if(v.getId()==R.id.sbinedit||v.getId()==R.id.productedit){
			next=getCurrentFocus();//无焦点是,找到最近一次操作的焦点
			if(next==null||next.getId()==R.id.confirm){
				next=view;
				if(next==null){
					return;
				}
			}
			int height=0;
			if(next.getId()==R.id.sbinedit){
				taskitem=(RelativeLayout) next.getParent().getParent().getParent();
			}else{
				taskitem=(RelativeLayout) next.getParent();
			}
			for(int i=0;i<tasklist.getChildCount();i++){
				height+=tasklist.getChildAt(i).getHeight()+itemmargin;
				if(taskitem==tasklist.getChildAt(i)){
					height-=tasklist.getChildAt(i).getHeight()+itemmargin;
					break;
				}
			}
			tasklistscroll.smoothScrollTo(0, height-40>0?height-40:height);
		}
	}
	
	private static class ScanHandler extends Handler {
		WeakReference<PickoutActivity> wactivity;
		ScanHandler(PickoutActivity activity) {
			wactivity = new WeakReference<PickoutActivity>(activity);
		}

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
			PickoutActivity activity = wactivity.get();
			switch (msg.what) {
			case ReadCodeController.CODEREAD:{
				HashMap<String, Object>params;
				if(msg.obj instanceof String){
					params=new HashMap<String, Object>();
					params.put(READCODEVALUE, msg.obj);
				}else{
					params=(HashMap<String, Object>)msg.obj;
				}
				try {
					activity.readcode(params.get(READCODEVALUE)+"",(View)params.get(FOCUSVIEW),msg.arg1!=AUTOREAD);
				} catch (DbException e) {
					e.printStackTrace();
				}
				break;
			}
			default:
				break;
			}
		}
	};

	private class ConfirmListener implements OnClickListener{
		@Override
		public void onClick(final View v) {
			RelativeLayout taskitem=(RelativeLayout)v.getParent();
			final BootstrapEditText productedit=(BootstrapEditText)taskitem.findViewById(R.id.productedit);
			BootstrapEditText sbinedit=(BootstrapEditText)taskitem.findViewById(R.id.sbinedit);
			if(StringUtil.isEmpty(sbinedit.getText().toString())){
				sbinedit.findViewById(R.id.sbinedit).requestFocus();
				Toast.makeText(PickoutActivity.this, "先选择仓位", Toast.LENGTH_SHORT).show();
				return;
			}else if(StringUtil.isEmpty(productedit.getText().toString())){
				Toast.makeText(PickoutActivity.this, "输入产品", Toast.LENGTH_SHORT).show();
				productedit.requestFocus();
				return;
			}
			productedit.requestFocus();
			new AlertDialog.Builder(PickoutActivity.this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Message msg=new Message();
					msg.what=ReadCodeController.CODEREAD;
					Map<String,Object> params=new HashMap<String, Object>();
					params.put(READCODEVALUE, productedit.getText().toString().trim().toUpperCase(Locale.US));
					params.put(FOCUSVIEW, productedit);
					msg.obj=params;
					sHandler.dispatchMessage(msg);
				}
			}).setTitle("提示").setMessage("捡取产品:"+productedit.getText()).setNegativeButton("取消", null).show();
			
		}
	}
	private class ReduceListener implements OnClickListener{
		@Override
		public void onClick(final View v) {
			final RelativeLayout taskitem=(RelativeLayout)v.getParent();
			TextView producttext=(TextView)taskitem.findViewById(R.id.producttextview);
			new AlertDialog.Builder(PickoutActivity.this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					TextView taskstatus=(TextView)taskitem.findViewById(R.id.taskstatus);
					TextView seq=(TextView)taskitem.findViewById(R.id.seq);
					try {
						EnquiryOrderItem eoi= db.findFirst(Selector.from(EnquiryOrderItem.class).where(WhereBuilder.b("whoseq", "=", seq.getText()+"")));
						eoi.setStatus(1);
						eoi.quantity=eoi.quantity-1<0?0:eoi.quantity-1;
						db.update(eoi, "status","quantity");
						taskstatus.setText(EnquiryOrderItem.STATUSDESC[eoi.status]);
						ProgressBar p=(ProgressBar)taskitem.findViewById(R.id.taskprogress);
						p.setProgress(eoi.quantity);
						PickoutActivity.this.refreshTotalProgress();
						play_sound(true);
					} catch (DbException e) {
						e.printStackTrace();
					}
				}
			}).setTitle("提示").setMessage("减少产品:"+producttext.getText()).setNegativeButton("取消", null).show();
			
		}
	}
	public void play_sound(boolean success) {
		try {
			if(success){
				mediaPlayer = MediaPlayer.create(this, R.raw.success);
			}else{
				mediaPlayer = MediaPlayer.create(this, R.raw.error);
			}
			mediaPlayer.stop();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static class WSHandler extends Handler {
		WeakReference<PickoutActivity> wactivity;
		WSHandler(PickoutActivity activity) {
			wactivity = new WeakReference<PickoutActivity>(activity);
		}

		public void handleMessage(Message msg) {
			PickoutActivity activity = wactivity.get();
			switch (msg.what) {
			case WebServicesUtil.ACTION_GetWHO:{
				if((msg.obj+"").startsWith("错误")){
					Toast.makeText(activity, msg.obj+"", Toast.LENGTH_SHORT).show();
					activity.wonoedit.setText("");
					break;
				}
				try {
					String result=msg.obj+"";
					Gson gson = new Gson();
					Type type = new TypeToken<JsonEnquiryOrder>() {}.getType();
					JsonEnquiryOrder jeo=gson.fromJson(result, type);
					if("".equals(result+"")){
						Toast.makeText(activity, activity.wonoedit.getText()+"数据为空", Toast.LENGTH_SHORT).show();
						activity.wonoedit.setText("");
						break;
					}else if(jeo!=null&&jeo.getITEMS()!=null&&jeo.getITEMS().size()==0){
						Toast.makeText(activity, activity.wonoedit.getText()+"任务队列为空", Toast.LENGTH_SHORT).show();
						activity.wonoedit.setText("");
						break;
					}
					PickOutInfo poi=activity.db.findFirst(PickOutInfo.class);
					if(poi!=null&&poi.isQueue()){//是否后续工作
						if(jeo==null){
							poi.setQueuename(activity.eo.getQueue());
						}else{
							poi.setQueuename(jeo.getQUEUE());
						}
						activity.db.update(poi, "queuename");
						activity.choosequeue.setText(poi.getQueuename());
						activity.choosequeue.setEnabled(false);
					}else if(poi==null||(poi!=null&&!poi.isQueue())){
						activity.choosequeue.setVisibility(View.GONE);
					}
					activity.wonotext.setVisibility(View.VISIBLE);
					activity.wonoedit.setVisibility(View.GONE);
					if(jeo==null){
						activity.wonotext.setText(Html.fromHtml("<u>"+activity.eo.getWho()+"</u>"));
					}else{
						activity.wonotext.setText(Html.fromHtml("<u>"+jeo.getWHO()+"</u>"));
					}
					if(msg.arg1!=CONTINUEWORK){
						activity.jsonToDbGetDetail(result);
					}
					activity.showTaskPage();
					activity.scrollview();
					} catch (DbException e) {
						e.printStackTrace();
					}
				break;
			}
			case WebServicesUtil.ACTION_SubmitWHO:{
				if((msg.obj+"").startsWith("错误")){
					activity.play_sound(false);
					Toast.makeText(activity, msg.obj+"", Toast.LENGTH_LONG).show();
					break;
				}
				Gson gson = new Gson();
				Type type = new TypeToken<TohuOut>() {}.getType();
				TohuOut tohuOut=gson.fromJson(msg.obj+"", type);
				tohuOut.setOUTPUT_HUIDENT(tohuOut.getOUTPUT_HUIDENT().replaceAll("^(0+)", ""));
				activity.ctnnoedit.setText(tohuOut.getOUTPUT_HUIDENT());
				boolean hasError=false;
				for (TohuOutMessage to : tohuOut.getMessages()) {
					if(to.getTYPE().contains("E")){
						hasError=true;
						activity.showresult.setBootstrapType("danger");
					}
				}
				activity.jsonToDbGetResult(tohuOut,hasError);
				try {
					activity.initResultWindow();
					if(!hasError){
						activity.play_sound(true);
						Toast.makeText(activity, "处理成功", Toast.LENGTH_LONG).show();
						activity.db.deleteAll(EnquiryOrder.class);
						activity.db.deleteAll(EnquiryOrderItem.class);
						Intent in=new Intent(activity,PickoutActivity.class);
						activity.startActivity(in);
						activity.finish();
					}
				} catch (DbException e) {
					e.printStackTrace();
				}
				break;
			}
			case WebServicesUtil.ACTION_LOGOUT:{
				//注销订单持有
				try {
					if((msg.obj+"").startsWith("错误")){
						activity.play_sound(false);
						Toast.makeText(activity, msg.obj+"", Toast.LENGTH_LONG).show();
						break;
					}
					activity.db.deleteAll(PickOutInfo.class);
					activity.db.deleteAll(EnquiryOrder.class);
					activity.db.deleteAll(EnquiryOrderItem.class);
					activity.db.deleteAll(TohuOutMessage.class);
					activity.db.deleteAll(TohuOut.class);
				} catch (DbException e) {
					e.printStackTrace();
				}
				activity.play_sound(true);
				Intent in=new Intent(activity,PickoutActivity.class);
				activity.startActivity(in);
				activity.finish();
				break;
			}
			case WebServicesUtil.ACTION_getQUEUE:{
				if((msg.obj+"").startsWith("错误")){
					activity.play_sound(false);
					Toast.makeText(activity, msg.obj+"", Toast.LENGTH_LONG).show();
					break;
				}
				Gson gson=new Gson();
				Type type = new TypeToken<List<WoQueue>>() {}.getType();
				List<WoQueue> wqList=gson.fromJson(msg.obj+"", type);
				activity.showQueueDialog(wqList);
				break;
			}
			case WebServicesUtil.ACTION_getWOByQUEUENAME:{
				PickOutInfo p=new PickOutInfo();
				p.setQueue(true);
				try {
					activity.db.save(p);
					msg.what=WebServicesUtil.ACTION_GetWHO;
					if(StringUtil.isEmpty(msg.obj+"")){
						return;
					}
					handleMessage(msg);
				} catch (DbException e) {
					e.printStackTrace();
				}
				break;
			}
			case WebServicesUtil.TIMEOUT:{
				new AlertDialog.Builder(activity).setPositiveButton("确定", null).setTitle("提示").setMessage("连接超时").show();
				break;
			}
			case WebServicesUtil.NETUNREACHABLE:{
				Toast.makeText(activity, "网络无法连接或连接已取消,请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
			if(activity.progressDialog!=null&&activity.progressDialog.isShowing()){
				activity.progressDialog.dismiss();
			}
		}
	};
	
	private void jsonToDbGetResult(TohuOut tohuOut,boolean hasError){
		try {
			db.deleteAll(TohuOut.class);
			db.deleteAll(TohuOutMessage.class);
			EnquiryOrder eo=db.findFirst(EnquiryOrder.class);
			eo.setEnded(!hasError);
			eo.setCtnno(tohuOut.getOUTPUT_HUIDENT());
			db.update(eo, "ended","ctnno");
			db.saveBindingIdAll(tohuOut.getMessages());
			db.saveBindingId(tohuOut);
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
	
	public void showQueueDialog(List<WoQueue> wqList) {
		// 创建dialog,listview 布局
		LinearLayout linearLayoutMain = new LinearLayout(this);// 自定义一个布局文件
		linearLayoutMain.setLayoutParams(new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		ListView deviceList = new ListView(this);// this为获取当前的上下文
		deviceList.setLayoutParams(new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		deviceList.setFadingEdgeLength(0);
		ArrayList<HashMap<String, String>> listItem=new ArrayList<HashMap<String, String>>();
		for (WoQueue woQueue : wqList) {
			HashMap<String, String> item=new HashMap<String, String>();
			item.put("textkey", woQueue.NOINTERLEAV);
			item.put("textvalue", woQueue.QUEUE);
			listItem.add(item);
		}
		SimpleAdapter listAdapter = new SimpleAdapter(this,listItem,//数据源   
	            R.layout.pickout_queue_name,//ListItem的XML实现  
	            //动态数组与ImageItem对应的子项          
	            new String[] {"textkey","textvalue"},   
	            //ImageItem的XML文件里面的一个ImageView,两个TextView ID  
	            new int[] {R.id.textkey,R.id.textvalue}  
	    );  
		deviceList.setAdapter(listAdapter);
		linearLayoutMain.addView(deviceList);
		// 显示dialog
		final AlertDialog dialog = new AlertDialog.Builder(this)
				.setTitle("选择队列")
				.setView(linearLayoutMain)
				// 在这里把写好的这个listview的布局加载dialog中
				.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						}).create();
		dialog.setCanceledOnTouchOutside(false);// 使除了dialog以外的地方不能被点击
		dialog.show();
		deviceList.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
//				TextView v=(TextView)view;
				TextView v=(TextView)view.findViewById(R.id.textvalue);
				String queuename=v.getText()+"";
				dialog.cancel();
				getWoByQueueName(queuename);
			}});
	}
	private void getWoByQueueName(String queuename) {
		if(StringUtil.isEmpty(queuename)){
			return;
		}
		HashMap<String, Object>params=new HashMap<String, Object>();
		params.put("QUEUENAME", queuename);
		Gson gson=new Gson();
		Type type = new TypeToken<User>() {}.getType();
		params.put("USER", gson.toJson(loginUser, type));
		progressDialog=ProgressDialog.show(PickoutActivity.this, "查询中", "请稍候...", true, true);
		ws.call(WebServicesUtil.ACTION_getWOByQUEUENAME, params, WebServicesUtil.URL_ACTION_getWOByQUEUENAME, WebServicesUtil.METHOD_ACTION_getWOByQUEUENAME);
	}
	private void jsonToDbGetDetail(String response){
		try {
			Gson gson = new Gson();
			Type type = new TypeToken<JsonEnquiryOrder>() {}.getType();
			eo = new EnquiryOrder();
			JsonEnquiryOrder jeo=gson.fromJson(response, type);
			eo.setWono(wonotext.getText().toString().trim().toUpperCase(Locale.US));
			eo.setWho(jeo.getWHO());
			eo.setUpdatetime(new Date(System.currentTimeMillis()));
			eo.setAreawho(jeo.getAREAWHO());
			eo.setLgnum(jeo.getLGNUM());
			eo.setPackprofile(jeo.getPackProFile());
			eo.setWcr(jeo.getWCR());
			eo.setQueue(jeo.getQUEUE());
			eo.setPackmatnr(jeo.getPACKMATNR());
			eo.setLs_attributes(jeo.getLS_ATTRIBUTES());
			eo.setEnded(false);
			db.saveBindingId(eo);
			List<JsonEnquiryOrderItem> list = jeo.ITEMS;
			int j=1;
			for (JsonEnquiryOrderItem jsonEnquiryOrder : list) {
				EnquiryOrderItem eoi=new EnquiryOrderItem();
				eoi.setJsonObj(jsonEnquiryOrder);
				eoi.productno=jsonEnquiryOrder.getMATNR();
				eoi.allquantity=jsonEnquiryOrder.getVSOLM();
				eoi.sbinno=jsonEnquiryOrder.getVLPLA();
				eoi.quantity=0;
				eoi.setSbinnocheck("");
				eoi.status=0;
				eoi.setSeq(j);
				eoi.setWhoseq(jsonEnquiryOrder.getWHOSEQ());
				db.saveBindingId(eoi);
				j++;
			}	
			gson = null;
			type = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void play_sound() {
		try {
			if (mediaPlayer == null)
				mediaPlayer = MediaPlayer.create(this, R.raw.noc);
			mediaPlayer.stop();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
